#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018\9\6 0006 20:33
# @Author  : never mind
# @File    : file_utils.py

import os
import io
import pickle, pprint
import numpy as np

import constants as cons



def save_file(filename, content, mode='wb'):
    # output = open(filename, mode=mode)
    # pickle.dump(content, output)
    # output.close()
    with open(filename, 'wb') as f:
        pickle.dump(content, f)
    print('save data done!')
    pass

def read_file(filename, mode='rb'):
    if not os.path.isfile(filename):
        print('%s is not a filename' % filename)
        return False
    # pkl_file = open(filename, mode=mode)
    # data = pickle.load(pkl_file)
    # pkl_file.close()
    # return data
    try:
        with open(filename, 'rb') as f:
            data = pickle.load(f)
            return data
    except EOFError:  # 捕获异常EOFError 后返回None
        print('file_utils.py EOF error')
        return False

def modify_file(filename, content, add_move, mode='rb'):
    if type(content) == list:
        data = read_file(filename) if read_file(filename) else []
        if add_move == cons.add:
            if content not in data:
                data.append(content)
        if content not in data:
            print('there is no such a position')
            return False
        if data and content in data and add_move == cons.remove:
            data.remove(content)
        save_file(filename, data)
        return True

    if type(content) == dict:
        content_keys = content.keys()
        content_values = content.values()
        data = read_file(filename) if read_file(filename) else {}

        if not os.path.isfile(filename):
            f = open(filename, 'w')
            f.close()
            print('%s is created' % filename)

        if add_move == cons.add:           # content -> key: value
            data.update(content)
        if add_move == cons.remove:        # content -> key
            data.pop(content)
        save_file(filename, data)
        print('update %s, %s: %s' % (filename, content_keys, content_values))
    pass

if __name__ == '__main__':
    data1 = {'a22': 'sdfasd', 'b': 123, 'c': None}
    list1 = [1, 2, 3]
    list1.append(list1)
    data2 = [[1, 2], [2, 3], [3, 4]]
    list2 = [4, 5]
    occ = [[4, 4]]
    read_file(cons.occupied_file)
    for item in occ:
        modify_file(cons.occupied_file, item, cons.add)

    # save_file('occ.pkl', data2)
    # read_file('occ.pkl')
    # modify_file('occ.pkl', list2, cons.remove)

    # save_file('data.pkl', data1)
    # read_file(cons.trace_file)
    # modify_file('data.pkl', data1, cons.add)

    # pos = [0, 2]
    # modify_file(cons.trace_file, pos, cons.add)